import os, email, time
from smtps import *

#
# A specialization of SMTPServerInterface for debug, that just prints its args.
#
class SMTPServerInterfaceStoreMail(SMTPServerInterface):
    """
    A debug instance of a SMTPServerInterface that just prints its
    args and returns.
    """
    detach_dir = ""

    def helo(self, args):
        print 'Received "helo"', args

    def mailFrom(self, args):
        print 'Received "MAIL FROM:"', args

    def rcptTo(self, args):
        self.detach_dir = stripAddress(args).split("@")[0]
        print 'Received "RCPT TO"', args

    def data(self, args):
	self.msg = email.message_from_string(args)
	for part in self.msg.walk():
             print part.keys()
             print part.get_content_type()
             # multipart/* are just containers
             if part.get_content_maintype() == 'multipart':
                 continue

             #is_attachment = part.get('Content-Disposition')
             #if is_attachment is None :
             #    #body = part.get_payload(decode=True)
             #    #print 'Body' , body
             #    continue
             if part.get_content_type() != 'image/pdf':
                 continue
             filename = "%s-%s.pdf"%(self.detach_dir, time.strftime("%Y_%m_%d-%H_%M"))
             counter = 1
             
             print 'Filename' , filename
             att_path = os.path.join(self.detach_dir, filename)
             #check if directory exists
             if not os.path.isdir(self.detach_dir):
                 os.mkdir(self.detach_dir)
             #Check if its already there
             if not os.path.isfile(att_path) :
                 fp = open(att_path, 'wb')
                 fp.write(part.get_payload(decode=True))
                 fp.close() 
                 pass

    def quit(self, args):
        print 'Received "QUIT"', args

    def reset(self, args):
        print 'Received "RSET"', args

if __name__ == '__main__':
    if len(sys.argv) == 2:
        port = int(sys.argv[1])
    else:
        port = 25
    s = SMTPServer(port)
    s.serve(impl=SMTPServerInterfaceStoreMail())

